var $zTree;
//url为请求ztree数据的url, idName：保存选中选项id的Html标签
function InitddTree(url,idName){
	//var pIdHidden=$('<input type="hidden" id='+idName+' name='+idName+'/>');
	var treeDiv=createzTree();
	$('.DropDownTree').after(treeDiv);
	$('.DropDownTree').attr("readonly", "readonly");
	initTree(url, null, $zTree, function (event, treeId, treeNode) {
		$('.DropDownTree').val(treeNode.name);
		$('#'+idName).val(treeNode.Id);
		treeDiv.hide();
	});
	$('.DropDownTree').click(function () {
	    treeDiv.toggle();
	});
	
}


//zTree相关操作
var initTree = function (url, data, $zTree,callback) {
    //数据定义
    var setting = {
        view: { selectedMulti: false },
        data: {
            key: {
                name: 'name',
                title: 'name'
            },
            simpleData: {
                enable: true,
                idKey: 'Id',
                pIdKey: 'pId',
                rootPId: '0'
            }
        },
        callback: {
            onClick: callback   //点击节点事件
        }
    }
    //请求ztree的数据
    $.post(url, data, function (json) {
        
        var msg = eval('(' + json + ')');
        var treeNodes = [];
        $.each(msg, function (i, d) {
            treeNodes.push({ "Id": d.Id, "name": d.Name, "pId": d.ParentId });
        });
        var zTree = $.fn.zTree.init($zTree, setting, treeNodes);
        zTree.expandAll(true);
    })
}


//创建zTree的DOM对象
function createzTree(){
	$zTree=$('<ul id="tree" class="ztree" style="padding: 5px;"></ul>');
	var $treeDiv=$('<div id="ddt_tree"></div>');
	var dwidth=$('.DropDownTree').css('width');
	
	$treeDiv.css({
	    "width": dwidth, "height": "200px", "position": "absolute",
	    "display": "none", "z-index": "10",
	    "overflow": "auto",
	    "background": "#fff",
        "border":"1px solid #ccc"
	});
	$treeDiv.append($zTree);
	return $treeDiv;

}

